package com.zimmor.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

import java.util.concurrent.TimeoutException;

/**
 * @Author:zimmor
 * @Date: 2021/12/28 17:22
 * @Description RabbitMQ客户端工具类
 * @version: 1.0.0
 */

public class RabbitmqUtil {
    private static  ConnectionFactory connectionFactory;

    static {
        //获取连接工厂
        connectionFactory = new ConnectionFactory();
        //设置主机server
        connectionFactory.setHost("192.168.204.51");
        //设置端口
        connectionFactory.setPort(5672);
        //设置要访问的虚拟机
        connectionFactory.setVirtualHost("/");
        //设置账户和密码
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
    }

    /**
     * 获取一个连接
     * @return
     */
    public static Connection getConnection() {

        try {

            //通过工厂生产一个连接
            Connection connection = connectionFactory.newConnection();
            return connection;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭连接和通道
     */
    public static void close(Channel channel, Connection connection) {
        try {
            if(channel != null) channel.close();
            if(connection != null) connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
